import React, { useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, FlatList, Alert, ActivityIndicator, Image, RefreshControl } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation, useFocusEffect } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import { Ionicons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import { RootStackParamList } from '../navigation/AppNavigator';
import { Colors } from '../constants/colors';

import { courseService } from '../services';
import { CourseVo } from '../types/api';

type CourseScreenNavigationProp = StackNavigationProp<RootStackParamList>;



export default function CourseManagementScreen() {
  const navigation = useNavigation<CourseScreenNavigationProp>();
  const [courses, setCourses] = useState<CourseVo[]>([]);
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState<number | null>(null);
  const [refreshing, setRefreshing] = useState(false);

  // 加载课程列表
  const loadCourses = async () => {
    try {
      setLoading(true);
      console.log('開始加載課程列表...');
      const result = await courseService.getCourseList({ pageNum: 1, pageSize: 50 });
      console.log('課程列表加載成功:', result);
      setCourses(result.rows || []);
    } catch (error: any) {
      console.error('加載課程列表失敗:', error);
      Alert.alert('錯誤', '加載課程列表失敗: ' + (error.message || '未知錯誤'));
    } finally {
      setLoading(false);
    }
  };

  // 下拉刷新处理
  const onRefresh = async () => {
    setRefreshing(true);
    await loadCourses();
    // 延迟一点时间再隐藏刷新指示器，提供更好的用户体验
    setTimeout(() => {
      setRefreshing(false);
    }, 500);
  };

  // 页面聚焦时重新加载数据
  useFocusEffect(
    React.useCallback(() => {
      loadCourses();
    }, [])
  );

  const handleAddCourse = () => {
    navigation.navigate('AddCourse');
  };

  // 处理课程上架/下架
  const handleTogglePublish = async (courseId: number, isPublished: boolean) => {
    try {
      setActionLoading(courseId);

      if (isPublished) {
        await courseService.unpublishCourse(courseId);
        Alert.alert('成功', '課程已下架');
      } else {
        await courseService.publishCourse(courseId);
        Alert.alert('成功', '課程已上架');
      }

      // 重新加載課程列表
      loadCourses();
    } catch (error: any) {
      console.error('課程上架/下架失敗:', error);
      Alert.alert('錯誤', error.message || '操作失敗');
    } finally {
      setActionLoading(null);
    }
  };

  const renderCourseCard = ({ item }: { item: CourseVo }) => {
    const isPublished = item.isPublished === '1';
    const isLoading = actionLoading === item.id;
    const courseTypeLabel = item.courseType === '0' ? '單人課' : '團體課';

    return (
      <View style={styles.courseCard}>
        {/* 课程类型标签 */}
        <View style={styles.courseTypeTag}>
          <Text style={styles.courseTypeText}>{courseTypeLabel}</Text>
        </View>

        {/* 状态标签 */}
        <View style={styles.statusTag}>
          <View style={[styles.statusDot, !isPublished && styles.statusDotGray]} />
          <Text style={[styles.statusText, !isPublished && styles.statusTextGray]}>
            {isPublished ? '已上架' : '已下架'}
          </Text>
        </View>

        <View style={styles.courseContent}>
          {/* 左侧图片 */}
          <View style={styles.courseImageContainer}>
            {item.coverImage ? (
              <Image source={{ uri: item.coverImage }} style={styles.courseImage} />
            ) : (
              <View style={styles.courseImagePlaceholder}>
                <Ionicons name="fitness" size={32} color={Colors.primary} />
              </View>
            )}
          </View>

          {/* 右侧内容 */}
          <View style={styles.courseInfo}>
            <Text style={styles.courseTitle} numberOfLines={2}>{item.title}</Text>

            <Text numberOfLines={3} style={styles.courseDescription}>
              課程介紹：{item.introduction || item.content || '有氧運動課程包括以下幾個環節：適度快速有力的跳躍，迅速提升心率，加速新陳代謝，消耗大量卡路里...'}
            </Text>

            {/*<Text style={styles.teacherInfo}>李小敏教練</Text>*/}

            <View style={styles.dateTimeContainer}>
              <Ionicons name="time-outline" size={12} color={Colors.gray[500]} />
              <Text style={styles.dateTimeText}>
                {item.startDate}-{item.endDate}
              </Text>
            </View>

            <View style={styles.bottomRow}>
              <View style={styles.priceContainer}>
                <Text style={styles.priceSymbol}>$</Text>
                <Text style={styles.priceAmount}>{item.price}</Text>
                <Text style={styles.priceUnit}>/節</Text>
              </View>

              <TouchableOpacity
                style={[
                  styles.actionButton,
                  isPublished ? styles.unpublishButton : styles.publishButton,
                  isLoading && styles.disabledButton
                ]}
                onPress={() => handleTogglePublish(item.id, isPublished)}
                disabled={isLoading}
              >
                {isLoading ? (
                  <ActivityIndicator size="small" color={Colors.white} />
                ) : (
                  <Text style={styles.actionButtonText}>
                    {isPublished ? '下架課程' : '上架課程'}
                  </Text>
                )}
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </View>
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      <LinearGradient colors={[Colors.gradientStart, Colors.gradientEnd]} style={styles.gradHeader}>
        <View style={styles.headerRow}>
          <Text style={styles.headerTitle}>課程管理</Text>
          <TouchableOpacity onPress={handleAddCourse} style={styles.addPill}>
            <Text style={styles.addPillText}>＋ 發佈課程</Text>
          </TouchableOpacity>
        </View>
      </LinearGradient>

      <View style={styles.content}>
        {loading ? (
          <View style={styles.loadingContainer}>
            <ActivityIndicator size="large" color={Colors.primary} />
            <Text style={styles.loadingText}>加載課程中...</Text>
          </View>
        ) : courses.length === 0 ? (
          <View style={styles.emptyState}>
            <Ionicons name="fitness-outline" size={64} color={Colors.gray[400]} />
            <Text style={styles.emptyTitle}>暫無課程</Text>
            <Text style={styles.emptyDescription}>點擊右上角新增按鈕創建您的第一個課程</Text>
            <TouchableOpacity onPress={handleAddCourse} style={styles.emptyButton}>
              <Text style={styles.emptyButtonText}>添加第一個課程</Text>
            </TouchableOpacity>
          </View>
        ) : (
          <FlatList
            data={courses}
            renderItem={renderCourseCard}
            keyExtractor={(item) => item.id.toString()}
            contentContainerStyle={styles.coursesList}
            showsVerticalScrollIndicator={false}
            refreshControl={
              <RefreshControl
                refreshing={refreshing}
                onRefresh={onRefresh}
                colors={[Colors.primary]}
                tintColor={Colors.primary}
              />
            }
          />
        )}
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.white,
  },
  gradHeader: {
    paddingTop: 12,
    paddingBottom: 16,
    paddingHorizontal: 16,
    borderBottomLeftRadius: 24,
    borderBottomRightRadius: 24,
  },
  headerRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  headerTitle: { color: Colors.white, fontSize: 20, fontWeight: '800' },
  addPill: { backgroundColor: Colors.white, paddingHorizontal: 12, paddingVertical: 6, borderRadius: 16 },
  addPillText: { color: Colors.primary, fontWeight: '700', fontSize: 12 },

  content: {
    flex: 1,
    padding: 16,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  loadingText: {
    marginTop: 16,
    fontSize: 16,
    color: Colors.gray[600],
  },
  emptyState: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 32,
  },
  emptyTitle: {
    fontSize: 20,
    fontWeight: '600',
    color: Colors.gray[700],
    marginTop: 16,
    marginBottom: 8,
  },
  emptyDescription: {
    fontSize: 16,
    color: Colors.gray[500],
    textAlign: 'center',
    lineHeight: 24,
    marginBottom: 24,
  },
  emptyButton: {
    paddingHorizontal: 24,
    paddingVertical: 12,
    backgroundColor: Colors.primary,
    borderRadius: 8,
  },
  emptyButtonText: {
    color: Colors.white,
    fontWeight: '600',
  },
  topRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingTop: 12,
  },
  badgeBlue: { backgroundColor: '#4F80FF', paddingHorizontal: 8, paddingVertical: 4, borderRadius: 10 },
  badgeText: { color: Colors.white, fontSize: 12, fontWeight: '600' },
  statusRight: { flexDirection: 'row', alignItems: 'center' },
  dotGreen: { width: 8, height: 8, borderRadius: 4, backgroundColor: Colors.success, marginRight: 6 },
  dotGray: { backgroundColor: Colors.gray[400] },
  statusRightText: { color: Colors.success, fontSize: 12, fontWeight: '600' },
  statusGrayText: { color: Colors.gray[600] },

  coursesList: {
    paddingVertical: 8,
  },
  courseCard: {
    backgroundColor: Colors.white,
    borderRadius: 16,
    marginBottom: 16,
    elevation: 4,
    shadowColor: Colors.black,
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 8,
    overflow: 'hidden',
    position: 'relative',
  },
  courseTypeTag: {
    position: 'absolute',
    top: 12,
    left: 12,
    backgroundColor: Colors.primary,
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 8,
    zIndex: 1,
  },
  courseTypeText: {
    color: Colors.white,
    fontSize: 12,
    fontWeight: '600',
  },
  statusTag: {
    position: 'absolute',
    top: 12,
    right: 12,
    flexDirection: 'row',
    alignItems: 'center',
    zIndex: 1,
  },
  statusDot: {
    width: 8,
    height: 8,
    borderRadius: 4,
    backgroundColor: Colors.success,
    marginRight: 4,
  },
  statusDotGray: {
    backgroundColor: Colors.gray[400],
  },
  statusText: {
    color: Colors.success,
    fontSize: 12,
    fontWeight: '600',
  },
  statusTextGray: {
    color: Colors.gray[600],
  },
  courseContent: {
    flexDirection: 'row',
    padding: 16,
  },
  courseImageContainer: {
    width: 100,
    height: 120,
    marginRight: 12,
  },
  courseHeader: {
    flexDirection: 'row',
    padding: 16,
  },
  courseImagePlaceholder: {
    width: '100%',
    height: '100%',
    backgroundColor: Colors.gray[100],
    borderRadius: 12,
    alignItems: 'center',
    justifyContent: 'center',
    overflow: 'hidden',
  },
  courseImage: {
    width: '100%',
    height: '100%',
    borderRadius: 12,
  },
  teacherInfo: {
    color: Colors.primary,
    fontSize: 12,
    fontWeight: '500',
    marginTop: 4,
    marginBottom: 6,
  },
  dateTimeContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 8,
  },
  dateTimeText: {
    color: Colors.gray[500],
    fontSize: 12,
    marginLeft: 4,
  },
  bottomRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginTop: 8,
  },
  priceContainer: {
    flexDirection: 'row',
    alignItems: 'baseline',
  },
  priceSymbol: {
    color: '#FF6B35',
    fontSize: 14,
    fontWeight: '600',
  },
  priceAmount: {
    color: '#FF6B35',
    fontSize: 18,
    fontWeight: '700',
  },
  priceUnit: {
    color: '#FF6B35',
    fontSize: 12,
    fontWeight: '600',
  },
  actionButton: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 20,
    minWidth: 80,
    alignItems: 'center',
    justifyContent: 'center',
  },
  publishButton: {
    backgroundColor: '#FF6B35',
  },
  unpublishButton: {
    backgroundColor: Colors.gray[400],
  },
  disabledButton: {
    opacity: 0.6,
  },
  actionButtonText: {
    color: Colors.white,
    fontSize: 12,
    fontWeight: '600',
  },
  // 保留一些有用的旧样式，删除重复的
  dateRow: { flexDirection: 'row', alignItems: 'center', marginBottom: 4 },
  timeRow: { flexDirection: 'row', alignItems: 'center' },
  dateText: { color: Colors.gray[500], fontSize: 12 },
  courseInfo: {
    flex: 1,
  },
  courseTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: Colors.gray[800],
    marginBottom: 4,
  },
  courseDescription: {
    fontSize: 14,
    color: Colors.gray[600],
    marginBottom: 8,
    lineHeight: 20,
  },
});
